// 目录: src/components/MyAutocomplete.js

import React, { useState, useEffect } from 'react';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import { Box } from '@mui/material';

export default function MyAutocomplete() {
  const [value, setValue] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [manualInput, setManualInput] = useState(''); // 用于存储手动输入的内容

  const options = ['Option 1', 'Option 2', 'Option 3'];

  useEffect(() => {
    // 当手动输入改变时，更新 inputValue，并且插入标签
    if (manualInput) {
      const insertedValue = manualInput
        .split(' ')
        .map((word, index) => {
          if (value.includes(word)) {
            return `<${word}>`;
          }
          return word;
        })
        .join(' ');

      setInputValue(insertedValue);
    }
  }, [manualInput, value]);

  return (
    <Box>
      <Autocomplete
        multiple
        freeSolo
        options={options}
        filterOptions={(options) => options}
        value={value}
        inputValue={inputValue}
        onInputChange={(event, newInputValue, reason) => {
          if (reason === 'input') {
            setManualInput(newInputValue); // 如果是用户输入，更新手动输入内容
          }
        }}
        onChange={(event, newValue) => {
          // 更新标签，同时处理标签的添加和删除
          setValue(newValue);
        }}
        renderInput={(params) => <TextField {...params} label="Choose Options" />}
      />
    </Box>
  );
}
